package com.yudean.esb.service.impl.erp;

import com.yudean.esb.dao.mds.MdsPLNAccountsDao;
import com.yudean.esb.dao.mds.MdsPLNDataDao;
import com.yudean.esb.dao.mds.MdsPLNEntitiesDao;
import com.yudean.esb.domain.mds.MdsPLNAccounts;
import com.yudean.esb.domain.mds.MdsPLNData;
import com.yudean.esb.domain.mds.MdsPLNEntities;
import com.yudean.esb.service.ERPPLNService;
import com.yudean.esb.security.SysAppUserService;
import com.yudean.esb.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.jws.WebService;
import java.util.List;

@WebService(endpointInterface = "com.yudean.esb.service.ERPPLNService", serviceName = "ERPPLNServiceService",targetNamespace = "http://service.esb.yudean.com/")
@Service
@Scope("prototype")
public class ERPPLNServiceImpl implements ERPPLNService {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(ERPPLNServiceImpl.class);

    @Resource
    private SysAppUserService sysAppUserService;

    static String perCompCode = "";
    static String perUserName = "";
    static String perPasswd = "";
    @Resource
    private MdsPLNEntitiesDao mdsPLNEntitiesDao;

    /**
     * @param year          年份
     * @param username      用户账号
     * @param password      用户密码
     * @return              按年份获取预算实体的信息
     */
    @Override
    public String getPLNEntitiesByYear(String year, String username, String password) {
        log.info("getAllPLNEntities():request:username-{}", username);
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        try {
            List<MdsPLNEntities> mdsPLNEntitiesList = mdsPLNEntitiesDao.getPLNEntitiesByYear(year);
            if (mdsPLNEntitiesList == null || mdsPLNEntitiesList.size() < 1) {
                return noData("getAllPLNEntities");
            }
            return wrapMdsPLNEntities2XML(mdsPLNEntitiesList);
        } catch (Exception e) {
            log.error("getAllPLNEntities():error-{}", e.getCause());
            return errorMsg("getAllPLNEntities", e.getMessage());
        }
    }

    @Resource
    private MdsPLNDataDao mdsPLNData;

    /**
     * @param pYear         年份
     * @param pScenario     情景
     * @param pVersion      版本
     * @param pSystem       系统代码"：“all”表示所有数据
     * @param username      用户名
     * @param password      密码
     * @return              按年份获取所有单位的预算数据
     */
    @Override
    public String getPlnDataYearly(String pYear, String pScenario, String pVersion, String pSystem, String username, String password) {
        log.info("getPlnDataYearly():request:{year-{},pScenario-{},pVersion-{},pSystem-{}}", pYear, pScenario, pVersion, pSystem);
        if (StringUtils.isBlank(pYear) || StringUtils.isBlank(pScenario) || StringUtils.isBlank(pVersion) || StringUtils.isBlank(pSystem)) {
            return noData("getPlnDataYearly");
        }
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        return getPlnDataYearly(pYear, pScenario, pVersion, pSystem);
    }

    private String getPlnDataYearly(String pYear, String pScenario, String pVersion, String pSystem) {
        try {
            List<MdsPLNData> mdsPLNDataList = mdsPLNData.getPlnDataYearly(pYear, pScenario, pVersion, pSystem);
            if (mdsPLNDataList == null || mdsPLNDataList.size() < 1) {
                return noData("getPlnDataYearly");
            }
            return wrapMdsPLNData2XML(mdsPLNDataList);
        } catch (Exception e) {
            log.error("getPlnDataYearly():error-{}", e.getCause());
            return errorMsg("getPlnDataYearly", e.getMessage());
        }
    }

    /**
     * @param pYear         年份
     * @param pScenario     情景
     * @param pVersion      期间
     * @param pSystem       系统代码"：“all”表示所有数据
     * @param username      用户名
     * @param password      密码
     * @param compCode      公司编码
     * @return              按年份、公司获取所在单位的预算数据
     */
    @Override
    public String getPlnDataYearlyByComp(String pYear, String pScenario, String pVersion, String pSystem, String username, String password, String compCode) {
        log.info("getPlnDataYearlyByComp():request:{year-{},pScenario-{},pVersion-{},pSystem-{}}", pYear, pScenario, pVersion, pSystem);
        if (StringUtils.isBlank(pYear) || StringUtils.isBlank(pScenario) || StringUtils.isBlank(pVersion) || StringUtils.isBlank(pSystem) || StringUtils.isBlank(compCode)) {
            return noData("getPlnDataYearlyByComp");
        }
        if (!sysAppUserService.hasPermit(compCode, username, password)) {
            return sysAppUserService.getErrMsg();
        }
        return getPlnDataYearlyByComp(pYear, pScenario, pVersion, pSystem, compCode);
    }

    private String getPlnDataYearlyByComp(String pYear, String pScenario, String pVersion, String pSystem, String compCode) {
        try {
            List<MdsPLNData> mdsPLNDataList = mdsPLNData.getPlnDataYearlyByComp(pYear, pScenario, pVersion, pSystem, compCode);
            if (mdsPLNDataList == null || mdsPLNDataList.size() < 1) {
                return noData("getPlnDataYearlyByComp");
            }
            return wrapMdsPLNData2XML(mdsPLNDataList);
        } catch (Exception e) {
            log.error("getPlnDataYearlyByComp():error-{}", e.getCause());
            return errorMsg("getPlnDataYearlyByComp", e.getMessage());
        }
    }

    /**
     * @param pScenario     情景
     * @param periodTrans   期间
     * @param pSystem       系统代码"：“all”表示所有数据
     * @param username      用户名
     * @param password      密码
     * @return              按期间获取所有单位的预算数据
     */
    @Override
    public String getPLNActualData(String pScenario, String periodTrans, String pSystem, String username, String password) {
        log.info("getPLNActualData():request:pScenario-{},,periodTrans-{},pSystem-{}", pScenario, periodTrans, pSystem);
        if (StringUtils.isBlank(pScenario) || StringUtils.isBlank(periodTrans) || StringUtils.isBlank(pSystem)) {
            return noData("getPLNActualData");
        }
        if ((username != "" && perCompCode.equals("YDZ") && perUserName.equals(username) && perPasswd.equals(password))
                || sysAppUserService.hasPermit("YDZ", username, password)) {
            perCompCode = "YDZ";
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        return getPLNActualData(pScenario, periodTrans, pSystem, null);
    }
    /**
     * @param pScenario     情景
     * @param periodTrans   期间
     * @param pSystem       系统代码"：“all”表示所有数据
     * @param username      用户名
     * @param password      密码
     * @param compCode      公司编码
     * @return              按期间获取所有单位的预算数据
     */
    @Override
    public String getPLNActualDataByComp(String pScenario, String periodTrans, String pSystem, String username, String password, String compCode) {
        log.info("getPLNActualDataByComp():request:pScenario-{},,periodTrans-{},pSystem-{}", pScenario, periodTrans, pSystem);
        if (StringUtils.isBlank(pScenario) || StringUtils.isBlank(periodTrans) || StringUtils.isBlank(pSystem) || StringUtils.isBlank(compCode)) {
            return noData("getPLNActualDataByComp");
        }
        if (!sysAppUserService.hasPermit(compCode, username, password)) {
            return sysAppUserService.getErrMsg();
        }
        return getPLNActualData(pScenario, periodTrans, pSystem, compCode);
    }

    private String getPLNActualData(String pScenario, String periodTrans, String pSystem, String compCode) {
        try {
            List<MdsPLNData> mdsPLNDataList = mdsPLNData.getPLNActualData(pScenario, periodTrans, pSystem,compCode);
            if (mdsPLNDataList == null || mdsPLNDataList.size() < 1) {
                return noData("getPLNActualData");
            }
            return wrapMdsPLNData2XML(mdsPLNDataList);
        } catch (Exception e) {
            log.error("getPLNActualData():error-{}", e.getCause());
            return errorMsg("getPLNActualData", e.getMessage());
        }
    }

    @Resource
    private MdsPLNAccountsDao mdsPLNAccountsDao;
    /**
     * @param username      用户账号
     * @param password      用户密码
     * @return              获取预算科目的信息
     */
    @Override
    public String getAllPLNAccounts(String username, String password) {
        log.info("getAllPLNAccounts():request:username-{}", username);
        if (sysAppUserService.hasPermit(null,username, password)) {
            perUserName = username;
            perPasswd = password;
        } else {
            return sysAppUserService.getErrMsg();
        }
        try {
            List<MdsPLNAccounts> mdsPLNAccountsList = mdsPLNAccountsDao.getAllPLNAccounts();
            if (mdsPLNAccountsList == null || mdsPLNAccountsList.size() < 1) {
                return noData("getAllPLNAccounts");
            }
            return wrapMdsPLNAccounts2XML(mdsPLNAccountsList);
        } catch (Exception e) {
            log.error("getAllPLNAccounts():error-{}", e.getCause());
            return errorMsg("getAllPLNAccounts", e.getMessage());
        }
    }

    private String wrapMdsPLNEntities2XML(List<MdsPLNEntities> mdsPLNEntitiesList) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("预算实体信息");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsPLNEntitiesList.size(); i++) {
            MdsPLNEntities mdsPLNEntitiy = mdsPLNEntitiesList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("name").setText(StringUtil.convertToString(mdsPLNEntitiy.getName()));
            data.addElement("description").setText(StringUtil.convertToString(mdsPLNEntitiy.getDescription()));
            data.addElement("path").setText(StringUtil.convertToString(mdsPLNEntitiy.getPath()));
            data.addElement("lev").setText(StringUtil.convertToString(mdsPLNEntitiy.getLev()));
            data.addElement("parentId").setText(StringUtil.convertToString(mdsPLNEntitiy.getParentId()));
            data.addElement("objectId").setText(StringUtil.convertToString(mdsPLNEntitiy.getObjectId()));
            data.addElement("erpCode").setText(StringUtil.convertToString(mdsPLNEntitiy.getErpCode()));
            data.addElement("year").setText(StringUtil.convertToString(mdsPLNEntitiy.getYear()));
            data.addElement("creationDate").setText(StringUtil.date2String(mdsPLNEntitiy.getCreationDate()));
            data.addElement("lastUpdatedDate").setText(StringUtil.date2String(mdsPLNEntitiy.getLastUpdatedDate()));
            data.addElement("createdBy").setText(StringUtil.convertToString(mdsPLNEntitiy.getCreatedBy()));
            data.addElement("lastUpdatedBy").setText(StringUtil.convertToString(mdsPLNEntitiy.getLastUpdatedBy()));
        }
        return root.asXML();
    }

    private String wrapMdsPLNAccounts2XML(List<MdsPLNAccounts> mdsPLNAccountsList) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("预算科目信息");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsPLNAccountsList.size(); i++) {
            MdsPLNAccounts mdsPLNAccount = mdsPLNAccountsList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("name").setText(StringUtil.convertToString(mdsPLNAccount.getName()));
            data.addElement("description").setText(StringUtil.convertToString(mdsPLNAccount.getDescription()));
            data.addElement("parentId").setText(StringUtil.convertToString(mdsPLNAccount.getParentId()));
            data.addElement("objectId").setText(StringUtil.convertToString(mdsPLNAccount.getObjectId()));
            data.addElement("creationDate").setText(StringUtil.date2String(mdsPLNAccount.getCreationDate()));
            data.addElement("lastUpdatedDate").setText(StringUtil.date2String(mdsPLNAccount.getLastUpdatedDate()));
            data.addElement("createdBy").setText(StringUtil.convertToString(mdsPLNAccount.getCreatedBy()));
            data.addElement("lastUpdatedBy").setText(StringUtil.convertToString(mdsPLNAccount.getLastUpdatedBy()));
        }
        return root.asXML();
    }

    private String wrapMdsPLNData2XML(List<MdsPLNData> mdsPLNDataList) {
        Document root = null;
        root = DocumentHelper.createDocument();
        Element element = root.addElement("service");
        element.addElement("name").setText("预算预实数据");
        element.addElement("type").setText("发布服务");
        Element datalist = element.addElement("datalist");
        for (int i = 0; i < mdsPLNDataList.size(); i++) {
            MdsPLNData mdsPLNData = mdsPLNDataList.get(i);
            Element data = datalist.addElement("data");
            data.addElement("years").setText(StringUtil.convertToString(mdsPLNData.getYears()));
            data.addElement("entity").setText(StringUtil.convertToString(mdsPLNData.getEntity()));
            data.addElement("department").setText(StringUtil.convertToString(mdsPLNData.getDepartment()));
            data.addElement("materials").setText(StringUtil.convertToString(mdsPLNData.getMaterials()));
            data.addElement("bu").setText(StringUtil.convertToString(mdsPLNData.getBu()));
            data.addElement("equipments").setText(StringUtil.convertToString(mdsPLNData.getEquipments()));
            data.addElement("products").setText(StringUtil.convertToString(mdsPLNData.getProducts()));
            data.addElement("customer").setText(StringUtil.convertToString(mdsPLNData.getCustomer()));
            data.addElement("version").setText(StringUtil.convertToString(mdsPLNData.getVersion()));
            data.addElement("scenario").setText(StringUtil.convertToString(mdsPLNData.getScenario()));
            data.addElement("periods").setText(StringUtil.convertToString(mdsPLNData.getPeriods()));
            data.addElement("account").setText(StringUtil.convertToString(mdsPLNData.getAccount()));
            data.addElement("value").setText(StringUtil.convertToString(mdsPLNData.getValue()));
            data.addElement("creationDate").setText(StringUtil.date2String(mdsPLNData.getCreationDate()));
            data.addElement("createdBy").setText(StringUtil.convertToString(mdsPLNData.getCreatedBy()));
            data.addElement("lastUpdateDate").setText(StringUtil.convertToString(mdsPLNData.getLastUpdatedBy()));
            data.addElement("lastUpdatedBy").setText(StringUtil.convertToString(mdsPLNData.getLastUpdatedBy()));
            data.addElement("periodTrans").setText(StringUtil.convertToString(mdsPLNData.getPeriodTrans()));
        }
        return root.asXML();
    }

    /**
     * 返回空数据的时候的信息
     *
     * @return
     */

    private String noData(String serviceName) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><service><name>" + serviceName + "</name><type>发布服务</type><datalist><!--查无数据--></datalist></service>";
    }

    /**
     * 返回查询出错信息
     *
     * @param msg
     * @return
     */
    private String errorMsg(String serviceName, String msg) {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?><service><name>" + serviceName + "</name><type>发布服务</type><datalist><!--error Message:" + msg + "--></datalist></service>";
    }


}
